#-*-coding:utf-8-*-

import sys,os,shutil
import xml.etree.ElementTree
addition_tail=" undistorted photos"
Dirs="ABCDE"
def cal_param(xml_file):
    same_dir=os.path.splitext(xml_file)[0]+addition_tail
    doc=xml.etree.ElementTree.parse(xml_file)
    pgs=doc.find("Block").find("Photogroups")
    for pg in pgs.findall("Photogroup"):
        focal_sensor=[1,1]
        for item in ("FocalLengthPixels","SensorSize"):
            try:
                value=float(pg.find(item).text)
                focal_sensor.append(value)
            except:
                print "%s Needed in xml file"%item
                #return 
        px,py=[float(pg.find("PrincipalPoint").find(x).text) for x in ("x","y")] 
        w,h=[float(pg.find("ImageDimensions").find(x).text) for x in ("Width","Height")]
        x0=px+0.5-w/2.
        y0=h/2-py-0.5
        ps=focal_sensor[0]*w/focal_sensor[1]
        target_dir=""
        for photo in pg.findall("Photo"):
            img_path=os.path.normpath(photo.find("ImagePath").text)
            img_name=os.path.split(img_path)[-1]
            print img_name+"\t"+img_path
            pd=img_name.split("_")[0]
            target_dir=os.path.join(same_dir,pd)
            if not os.path.exists(target_dir):
                os.mkdir(target_dir)
            new_img_path=os.path.join(target_dir,img_name)
            if os.path.exists(new_img_path):
                print type(new_img_path)
            shutil.move(os.path.join(same_dir,img_name).decode("utf-8"),new_img_path.decode("utf-8"))
            photo.find("ImagePath").text=new_img_path
        with open(os.path.join(target_dir,"param.txt"),'w') as f:
            f.write(" ".join([str(x) for x in [x0,y0,ps,0,0,0]]))
    doc.save("Where")

def group_files(_d):
     for _ in set([x.split("_")[0].upper() for x in os.listdir(_d)]):
         try:
            dis_dir=os.path.join(_d,_)
            os.mkdir(dis_dir)
            for _f in glob.glob(os.path.join(_d,"*")):
                if os.path.isfile(_f):
                    shutil.move(_f,os.path.join(_d,_d,_f))
         except:
             pass
def usage():
    print """
Script For deading the text generated by Smart3D and that one
    Step 1:rename and group the original pictures
    Step 2:Build Areath with Smart3D and export the params to xml file
    Step 3:Group the export pictures by profix name and correct\n\t\tpic path in xml file exported in step 2    
    Step 4:
    """   
def rename_dir(_d):
    """
    Happen in step One
    """
    cter=0
    fail_cter=0
    for d,ds,fs in os.walk(_d):
        if os.path.split(d)[-1].startswith("#"):
            continue
        for _i,_f in enumerate(fs):
            target_name=os.path.join(d,os.path.basename(d)+str(_i).zfill(4)+"."+_f.split(".")[-1])
            try:
                os.rename(os.path.join(d,_f),target_name)
                cter+=1
            except:
                print "Rename %s to %s fail"%(_f,target_name)
                fail_cter+=1
    return cter,fail_cter
def step_01(_path):
    print "Building dirs..."
    suc=0
    for d in Dirs:
        td=os.path.join(_path,d)
        if not os.path.exists(td):
            try:
                os.makedirs(td)
            except:
                suc=1
    return suc
def step_02(_path):
    rename_dir(_path)
def step_03(_file):
    calc_param(_file)
if __name__=="__main__":
    funcs=[0,step_01,step_02,step_03]
    len_arg=len(sys.argv)
    if len_arg==3:
        sys.exit(funcs[int(sys.argv[1][1])](sys.argv[-1]))
    elif len_arg==1:
        usage()
